package com.intelligentclass.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.intelligentclass.entity.Collection;
import com.intelligentclass.entity.Comment;
import com.intelligentclass.services.CollectionService;
import com.intelligentclass.services.CommentService;
import com.intelligentclass.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/collection")
public class CollectionController {

    @Autowired
    private CollectionService collectionService;

    @Autowired
    private CommentService commentService;

    @PostMapping("/collect")
    public ResponseEntity<?> collectComment(@RequestParam("commentId") int commentId,
                                            @RequestHeader("Authorization") String token) {
        try {
            // 去掉 "Bearer " 前缀
            token = token.replace("Bearer ", "");

            // 验证并解析 token
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
            String username = decodedJWT.getClaim("username").asString();

            // 更新 token
            token = JWTUtil.updateToken(token);

            // 创建并保存收藏记录
            Collection collection = new Collection();
            collection.setCollectionCommentId(commentId);
            collection.setCollectionSno(username);

            Collection savedCollection = collectionService.saveCollection(collection);

            // 构造响应数据
            Map<String, Object> response = new HashMap<>();
            response.put("savedCollection", savedCollection);
            response.put("updatedToken", token);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            return ResponseEntity.status(401).body("Invalid or expired token");
        }
    }

    //调用收藏的收藏夹时，username里面填入得到的guest
    @GetMapping("/all")
    public ResponseEntity<?> getAllCollections(@RequestHeader("Authorization") String token,
                                               @RequestParam(value = "username", required = false) String inputUsername) {
        try {
            // 如果没有提供 username，则从 token 中提取
            if (inputUsername == null || inputUsername.isEmpty()) {
                token = token.replace("Bearer ", "");
                DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
                inputUsername = decodedJWT.getClaim("username").asString();
            }

            // 定义一个局部的最终变量
            final String username = inputUsername;

            // 获取该用户的所有收藏记录
            List<Collection> userCollections = collectionService.findCollectionsBySno(username);

            // 构建响应数据列表，每个收藏记录对应一个详细的评论信息
            List<Map<String, Object>> userComments = userCollections.stream()
                    .map(collection -> {
                        Comment comment = commentService.findCommentByCommentId(collection.getCollectionCommentId());
                        Map<String, Object> commentData = new HashMap<>();
                        commentData.put("id", comment.getCommentId());
                        commentData.put("sno", comment.getCommentSno());
                        commentData.put("sname", comment.getCommentSname());
                        commentData.put("times", comment.getCommentTime());
                        commentData.put("text", comment.getCommentText());

                        // 判断用户是否收藏（点赞）了该评论
                        boolean isLiked = collectionService.existsByCommentIdAndSno(comment.getCommentId(), username);
                        commentData.put("like", isLiked ? 1 : 0);

                        // 设置文件资源的下载 URL
                        if (comment.getCommentLink() != null) {
                            String fileUrl = URLEncoder.encode(comment.getCommentLink(), StandardCharsets.UTF_8);
                            commentData.put("fileResourceUrl", fileUrl);
                        } else {
                            commentData.put("fileResourceUrl", "null");
                        }

                        // 设置图片资源的下载 URL
                        if (comment.getCommentImage() != null) {
                            String imageUrl = URLEncoder.encode(comment.getCommentImage(), StandardCharsets.UTF_8);
                            commentData.put("imageResourceUrl", imageUrl);
                        } else {
                            commentData.put("imageResourceUrl", "null");
                        }

                        return commentData;
                    })
                    .collect(Collectors.toList());

            // 构造最终的响应数据
            Map<String, Object> response = new HashMap<>();
            response.put("userComments", userComments);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            return ResponseEntity.status(401).body("Invalid or expired token");
        }
    }



    @PostMapping("/cancel")
    public ResponseEntity<?> cancelCollection(@RequestParam("commentId") int commentId,
                                              @RequestHeader("Authorization") String token) {
        try {
            // 去掉 "Bearer " 前缀
            token = token.replace("Bearer ", "");

            // 验证并解析 token
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
            String username = decodedJWT.getClaim("username").asString();

            // 检查收藏是否存在
            Collection collection = collectionService.findByCommentIdAndSno(commentId, username);
            if (collection == null) {
                return ResponseEntity.status(404).body("Collection not found");
            }

            // 删除收藏记录
            collectionService.deleteCollection(collection);

            // 更新 token
            token = JWTUtil.updateToken(token);

            // 构造响应数据
            Map<String, Object> response = new HashMap<>();
            response.put("message", "Collection cancelled successfully");
            response.put("updatedToken", token);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            return ResponseEntity.status(401).body("Invalid or expired token");
        }
    }
}
